class PostsController < ApplicationController

  before_filter :login_required

  # GET /posts
  # GET /posts.xml
  def index
    if logged_in? and current_user.admin == true
      @posts = Post.find(:all)
    else 
      @posts = Post.find :all, :conditions => ['private = false']
    end
    respond_to do |format|
      format.html # index.rhtml
      format.xml  { render :xml => @posts.to_xml }
    end
  end

  # GET /posts/1
  # GET /posts/1.xml
  def show
    @post = Post.find(params[:id])

    respond_to do |format|
      format.html # show.rhtml
      format.xml  { render :xml => @post.to_xml }
    end
  end

  # GET /posts/new
  def new
    @post = Post.new
  end

  # GET /posts/1;edit
  def edit
    @post = Post.find(params[:id])
  end

  # POST /posts
  # POST /posts.xml
  def create
    @post = Post.new(params[:post])
    @post.user_id = current_user
    @post.image = Image.new(params[:image])
    @post.image.user_id = current_user
    @post.image.post_id = @post.id
    respond_to do |format|
      if @post.save and @post.image.save
        flash[:notice] = 'Post was successfully created.'
        format.html { redirect_to post_url(@post) }
        format.xml  { head :created, :location => post_url(@post) }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @post.errors.to_xml }
      end
    end
  end

  # PUT /posts/1
  # PUT /posts/1.xml
  def update
    @post = Post.find(params[:id])

    respond_to do |format|
      if @post.update_attributes(params[:post])
        flash[:notice] = 'Post was successfully updated.'
        format.html { redirect_to post_url(@post) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @post.errors.to_xml }
      end
    end
  end

  # DELETE /posts/1
  # DELETE /posts/1.xml
  def destroy
    @post = Post.find(params[:id])
    @post.image.destroy
    @post.comments.each { |c| c.destroy }
    @post.destroy

    respond_to do |format|
      format.html { redirect_to posts_url }
      format.xml  { head :ok }
    end
  end

   def comment
     @comments = Post.find(params[:id]).comments
     @comment = @comments.create(params[:comment])
  end

end
